package com.yc.fav.servlet;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yc.base.servlet.BaseServlet;
import com.yc.base.util.Utils;
import com.yc.base.vo.Result;
import com.yc.fav.entity.User;
import com.yc.fav.mapper.UserMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import org.example.util.MyBatisUtils;

import java.io.IOException;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {

    public Object login(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        Utils.checkEmpty(username, "用户名不能为空")
             .checkEmpty(password, "密码不能为空");
        try(SqlSession session = MyBatisUtils.getSession();){
            UserMapper mapper = session.getMapper(UserMapper.class);
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getName, username)
               .eq(User::getPwd, password);
            User user = mapper.selectOne(lqw);
            Utils.checkEmpty(user, "用户名或密码错误");
            req.getSession().setAttribute("loginedUser", user);
            user.setPwd(null);
            return Result.ok("登录成功!", user);
        }
    }

    public Object logout(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.getSession().invalidate();
        return Result.ok("退出成功!");
    }

    public Object myinfo(HttpServletRequest req, HttpServletResponse resp) {
        User user = (User) req.getSession().getAttribute("loginedUser");
        Utils.checkEmpty(user, "请先登录!");
        return Result.ok("已登录",user);
    }
}
